package org.lhl.readruler.manager

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
import android.provider.Settings
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import com.blankj.utilcode.util.FragmentUtils
import lhl.kotlinextends.toast
import org.lhl.readruler.mApp


object MyLocationManager {

    val REQUEST_CODE_GPS = 0x33

    var myLocation: Location? = null

    private val locationManager: LocationManager? by lazy { mApp.getSystemService(Context.LOCATION_SERVICE) as LocationManager? }

    private lateinit var fm: FragmentManager
    @SuppressLint("MissingPermission")
    fun start(fm: FragmentManager) {
        this.fm = fm
        if (!isGpsEnable()) {
            "先打开GPS".toast()
            val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
            getFragment(fm).startActivityForResult(intent, REQUEST_CODE_GPS)
            return
        }
        locationManager?.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 0.5f, locationListener)
    }

    fun isGpsEnable(): Boolean = locationManager?.isProviderEnabled(LocationManager.GPS_PROVIDER) ?: false

    private val locationListener = object : LocationListener {
        override fun onLocationChanged(location: Location?) {
            myLocation = location
        }

        override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {
        }

        override fun onProviderEnabled(provider: String?) {
        }

        override fun onProviderDisabled(provider: String?) {
            "先打开GPS".toast()
            val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
            getFragment(fm).startActivityForResult(intent, REQUEST_CODE_GPS)
        }
    }

    fun onStop() {
        locationManager?.removeUpdates(locationListener)
    }

    private fun getFragment(fm: FragmentManager): Fragment {
        return FragmentUtils.findFragment(fm, "GpsBlankFragment") ?: kotlin.run {
            GpsBlankFragment().apply {
                fm.beginTransaction()?.add(this, "GpsBlankFragment")?.commitAllowingStateLoss()
                fm.executePendingTransactions()
            }
        }
    }

    class GpsBlankFragment : Fragment() {
        override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
            super.onActivityResult(requestCode, resultCode, data)
            if (requestCode == REQUEST_CODE_GPS) {
                start(fm)
            }
        }
    }

}